<template>
  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="30%" align-center>
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="类型编码" prop="type_code">
        <ElInput v-model="formData.type_code" placeholder="请输入类型编码" />
      </ElFormItem>
      <ElFormItem label="类型名称" prop="type_name">
        <ElInput v-model="formData.type_name" placeholder="请输入类型名称" />
      </ElFormItem>
      <ElFormItem label="描述" prop="type_desc">
        <ElInput v-model="formData.type_desc" type="textarea" placeholder="请输入描述" />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" v-ripple>提交</el-button>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { createDictType, updateDictType, type DictTypeResponse } from '@/api/system/dict'

interface Props {
  visible: boolean
  type: 'add' | 'edit'
  editData?: Partial<DictTypeResponse>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const dialogTitle = computed(() => (props.type === 'add' ? '添加字典类型' : '编辑字典类型'))

// 表单实例
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  type_code: '',
  type_name: '',
  type_desc: ''
})

// 校验规则
const rules: FormRules = {
  type_code: [{ required: true, message: '请输入类型编码', trigger: 'blur' }],
  type_name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }]
}

// 初始化表单
const initFormData = () => {
  const isEdit = props.type === 'edit' && props.editData
  const row = props.editData || {}
  Object.assign(formData, {
    type_code: isEdit ? (row.type_code || '') : '',
    type_name: isEdit ? (row.type_name || '') : '',
    type_desc: isEdit ? (row.type_desc || '') : ''
  })
}

watch(
  () => [props.visible, props.type, props.editData],
  async ([visible]) => {
    if (visible) {
      initFormData()
      nextTick(() => formRef.value?.clearValidate())
    }
  },
  { immediate: true }
)

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    const payload = {
      type_code: formData.type_code,
      type_name: formData.type_name,
      type_desc: formData.type_desc || null
    }

    try {
      if (props.type === 'add') {
        await createDictType(payload)
      } else {
        const id = Number(props.editData?.id)
        if (!id) {
          ElMessage.error('缺少字典类型ID，无法编辑')
          return
        }
        await updateDictType(id, payload)
      }
      ElMessage.success('提交成功')
      emit('submit')
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请稍后重试')
    }
  })
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>